<template>
  <div class="box">
    <!--<img :src="bg" alt="" class="bg">-->
    <div class="login">
      <div class="login_box">
        <div class="logo">
          <div class="name">
            <span>设备管理系统</span>
            <span>拒绝为用户增加工作量</span>
          </div>
          <img :src="landmark" alt class="landmark" />
        </div>
        <div class="form" v-show="!find">
          <p class="tabs">
            <span
              :class="{ active: active === 'first' }"
              @click="handleClick('first')"
              >用户密码登录</span
            >
            <span
              :class="{ active: active === 'second' }"
              @click="handleClick('second')"
              >手机验证码登录</span
            >
            <!-- <span :class="{'active':active==='three'}" @click="handleClick('three')">用户注册</span> -->
          </p>
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            class="ruleForm"
          >
            <el-form-item prop="userName" v-if="active === 'first'">
              <el-input
                ref="phone"
                :readonly="readonly"
                @blur="onBlur"
                @focus="onFocus"
                v-model="ruleForm.userName"
                prefix-icon="el-icon-mobile-phone"
                placeholder="请输入用户名"
                clearable
                autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item prop="password" v-if="active === 'first'">
              <el-input
                ref="password"
                @blur="onBlur"
                @focus="onFocus"
                :readonly="readonly"
                type="password"
                v-model="ruleForm.password"
                prefix-icon="el-icon-lock"
                placeholder="请输入密码"
                clearable
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item prop="phone" v-if="active === 'second'">
              <el-input
                ref="phone"
                :readonly="readonly"
                @blur="onBlur"
                @focus="onFocus"
                v-model="ruleForm.phone"
                prefix-icon="el-icon-mobile-phone"
                placeholder="请输入手机号"
                clearable
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item prop="message" v-if="active === 'second'">
              <el-input
                ref="message"
                maxlength="6"
                v-model="ruleForm.message"
                prefix-icon="el-icon-message"
                placeholder="短信验证码"
                clearable
                autocomplete="off"
              >
                <el-button
                  type="text"
                  slot="suffix"
                  class="code"
                  @click="sendCode"
                  :disabled="disabled"
                  >{{ text }}</el-button
                >
              </el-input>
            </el-form-item>
            <el-form-item prop="agreement">
              <p
                style="display: flex;align-items: center;justify-content: space-between;"
              >
                <span>
                  <el-checkbox
                    v-model="ruleForm.agreement"
                    @change="handleChange"
                    >我已阅读并同意</el-checkbox
                  >
                  <span class="user" @click="onChange(true)"
                    >《用户服务协议》</span
                  >
                </span>
                <span class="user" @click="forget">忘记密码</span>
              </p>
            </el-form-item>

            <!-- 用户注册
            <div style="font-size:14px;color:red">
              如果你没有账号,请
              <el-link type="success" @click.native="handlerRegister">立即注册</el-link>
            </div>-->
            <el-form-item>
              <el-button
                class="submitBtn"
                type="primary"
                native-type="submit"
                @click.prevent="submitForm('ruleForm')"
                size="small"
                :loading="loading"
                v-if="active === 'first' || active === 'second'"
              >
                <span
                  class="el-icon-right"
                  style="margin-right: 8px;"
                  v-show="!loading"
                ></span>
                {{ loading ? "登录中..." : "登 录" }}
              </el-button>
            </el-form-item>
            <!-- <Register v-if="active==='three'" /> -->
          </el-form>
        </div>

        <div class="form" v-show="find">
          <p class="tabs">
            <span class="active" style="margin-left: 0;">找回密码</span>
          </p>
          <Forget @changeLogin="changeLogin" />
        </div>
      </div>
    </div>
    <Agreement
      v-if="active === 'first' || active === 'second'"
      :visible="visible"
      @onChange="onChange"
      @onConfirm="onConfirm"
    />
  </div>
</template>
<script>
import Forget from "./Forget";
import Agreement from "./Agreement";
import { mapState } from "vuex";
import Register from "./Register";
import md5 from "md5";
import {
  userNameLogin,
  phoneLogin,
  messageSend,
  powerSelNoPage,
  joinGroup
} from "../../utils/api";

// const role = [
//   {
//     id: 1,
//     parentId: 0,
//     url: "/Home",
//     name: "主页"
//   },
//   {
//     id: 2,
//     parentId: 0,
//     url: "/Project",
//     name: "项目中心",
//     child: [
//       {
//         id: 10,
//         parentId: 2,
//         url: "/particulars",
//         name: "实时监控"
//       },
//       {
//         id: 11,
//         parentId: 2,
//         url: "/addRole",
//         name: "角色管理"
//       },
//       {
//         id: 12,
//         parentId: 2,
//         url: "/RoleContent",
//         name: "角色管理"
//       },
//       {
//         id: 28,
//         parentId: 2,
//         url: "/Offcurve",
//         name: "历史曲线"
//       }
//     ]
//   },
//   {
//     id: 3,
//     parentId: 0,
//     url: "/DeviceControl",
//     name: "设备管理"
//   },
//   {
//     id: 4,
//     parentId: 0,
//     url: "/WorkOrder",
//     name: "工单系统",
//     child: [
//       {
//         id: 18,
//         parentId: 4,
//         url: "/NowokOrder",
//         name: "代办工单"
//       },
//       {
//         id: 19,
//         parentId: 4,
//         url: "/JobignoredOrder",
//         name: "已忽略工单"
//       },
//       {
//         id: 20,
//         parentId: 4,
//         url: "/AcceptedWorkOrder",
//         name: "已受理工单"
//       },
//       {
//         id: 21,
//         parentId: 4,
//         url: "/WorkOrderConfirmed",
//         name: "待确认工单"
//       },
//       {
//         id: 22,
//         parentId: 4,
//         url: "/ConfirmedWorkOrder",
//         name: "已确认工单"
//       },
//       {
//         id: 23,
//         parentId: 4,
//         url: "/TaskDispatch",
//         name: "任务派单"
//       }
//     ]
//   },
//   {
//     id: 5,
//     parentId: 0,
//     url: "/ServiceProvider",
//     name: "服务商设置",
//     child: [
//       {
//         id: 13,
//         parentId: 5,
//         url: "/ServerList",
//         name: "服务商列表"
//       },
//       {
//         id: 14,
//         parentId: 5,
//         url: "/MaintenanceStaff",
//         name: "维修员工列表"
//       },
//       {
//         id: 15,
//         parentId: 5,
//         url: "/BaoStaff",
//         name: "保养员工列表"
//       }
//     ]
//   },
//   {
//     id: 6,
//     parentId: 0,
//     url: "/MaintainCenter",
//     name: "维修中心",
//     child: [
//       {
//         id: 24,
//         parentId: 6,
//         url: "/MaintenanRecords",
//         name: "维修列表"
//       },
//       {
//         id: 25,
//         parentId: 6,
//         url: "/shebeiList",
//         name: "设备列表"
//       },
//       {
//         id: 26,
//         parentId: 6,
//         url: "/MaintainDetial",
//         name: "查看详情"
//       }
//     ]
//   },
//   {
//     id: 7,
//     parentId: 0,
//     url: "/MaintenanceCenter",
//     name: "保养中心",
//     child: [
//       {
//         id: 16,
//         parentId: 7,
//         url: "/MaintenanceRecords",
//         name: "保养记录"
//       },
//       {
//         id: 17,
//         parentId: 7,
//         url: "/EquipmentList",
//         name: "设备列表"
//       },
//       {
//         id: 27,
//         parentId: 7,
//         url: "/MaintainceDetial",
//         name: "查看详情"
//       }
//     ]
//   },
//   {
//     id: 8,
//     parentId: 0,
//     url: "/OperatingRecord",
//     name: "操作记录"
//   },
//   {
//     id: 9,
//     parentId: 0,
//     url: "/personnel",
//     name: "工作人员",
//     child: [
//       {
//         id: 28,
//         parentId: 9,
//         url: "/PersonJob",
//         name: "工作人员"
//       },
//       {
//         id: 29,
//         parentId: 9,
//         url: "/PersionRole",
//         name: "角色管理"
//       },
//       {
//         id: 30,
//         parentId: 9,
//         url: "/PersionPerssion",
//         name: "权限管理"
//       },
//       {
//         id: 31,
//         parentId: 9,
//         url: "/PersonAddRole",
//         name: "添加角色"
//       },
//       {
//         id: 32,
//         parentId: 9,
//         url: "/Assignment",
//         name: "权限分配"
//       }
//     ]
//   },
//   {
//     id: 10,
//     parentId: 0,
//     url: "/UserSetting",
//     name: "个人设置"
//   }
// ];
// const role = [];
export default {
  name: "Login",
  inject: ["handlergetWarningListSimple", "showtost2"],
  data() {
    const validatePass = (rule, value, callback) => {
      const reg = /^[0-9A-Za-z]{6,16}$/;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的密码"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      const reg = /^1\d{10}$/;
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    const validateAgreement = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请阅读用户服务协议并确认勾选"));
      } else {
        callback();
      }
    };
    return {
      bg: require("../../assets/images/bilibili.png"),
      landmark: require("../../assets/images/landmark.png"),
      btn: require("../../assets/images/button.png"),
      active: "first",
      visible: false,
      readonly: true,
      loading: false,
      ruleForm: {
        password: "",
        phone: "",
        agreement: false,
        message: "",
        userName: ""
      },
      rules: {
        password: [{ validator: validatePass, trigger: "change" }],
        phone: [{ validator: validatePhone, trigger: "change" }],
        agreement: [{ validator: validateAgreement, trigger: "change" }],
        message: [
          { required: true, message: "请输入短信验证码", trigger: "change" }
        ]
      },
      text: "获取验证码",
      timer: null,
      disabled: false, //禁用发送按钮
      find: false, //忘记密码
      sendCoude: 60,
      // 角色列表
      role: [],
      // 角色id
      roleId: "",
      userId: "",
      // 权限id
      permissionId: "",
      websocket: null
    };
  },
  created() {
    var result = window.sessionStorage.getItem("sendCode");
    if (result == "" || result == null || result == undefined) {
      this.sendCoude = 60;
    } else {
      this.timer = setInterval(() => {
        this.disabled = true;
        result--;
        this.text = "已发送 " + result + "s";
        window.sessionStorage.setItem("sendCode", result);
        if (result <= 0) {
          clearInterval(this.timer);
          this.result = "";
          window.sessionStorage.removeItem("sendCode");
          this.text = "获取验证码";
          this.disabled = false;
        }
      }, 1000);
    }
    const that = this;
    that.$store.commit("SAVE");

    that.ruleForm.agreement = this.persistence.agreement;
    window.addEventListener("popstate", that.back(), false);
    this.showtost2();
    // this.sendCoude = window.sessionStorage.getItem("sendCode");
  },
  computed: {
    ...mapState(["menus", "persistence"])
  },
  mounted() {
    //  this.postRequest(joinGroup, {
    //       client_id: JSON.parse(data["data"])["client_id"]
    //     }).then(res => {});
  },
  methods: {
    websocketTest() {
      //初始化websocket
      // var url="ws://123.207.89.57:8282";
      // var url = "ws://47.99.74.117:8002";
      var url = "wss://tcp.wadd.vip/wss";

      this.websocket = new WebSocket(url);
      this.websocket.onmessage = this.websocketonmessage;
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      // this.websocket.onclose = this.websocketclose;
    },
    websocketonopen() {
      window.console.log("连接成功");
      var data = {
        type: "login",
        device_id: "socketGroup" + this.userId + 2
      };
      var arr = JSON.stringify(data);
      this.websocket.send(arr);

      // this.heatBeat();
    }, //连接成功
    websocketonerror() {
      window.console.log("连接失败");
      this.reconnect();
    }, //连接失败
    websocketclose() {
      window.console.log("断开连接");
      this.reconnect();
    },
    websocketonmessage(data) {
      console.log(data);

      if (JSON.parse(data["data"])["type"] == "login") {
        const aa = JSON.parse(data["data"])["client_id"];
        window.sessionStorage.setItem("clientId", aa);

        var data1 = {
          type: "ping"
        };
        var arr1 = JSON.stringify(data1);
        setInterval(() => {
          this.websocketsend(arr1);
        }, 5000);
        //调接口
        this.postRequest(joinGroup, {
          client_id: JSON.parse(data["data"])["client_id"]
        }).then(res => {});
      }

      if (JSON.parse(data["data"])["type"] == "report") {
        //调接口
        this.handlergetWarningListSimple();
      }

      if (JSON.parse(data["data"])["type"] == "pong") {
        if (
          JSON.parse(data["data"])["client_id"] ==
          window.sessionStorage.getItem("clientId")
        ) {
        } else {
          this.websocketTest();
        }
      }

      //收到消息会刷新心跳检测，如果一直收到消息，就推迟心跳发送
      // this.heatBeat();
    }, //数据接收
    websocketsend(data) {
      console.log(data);
      // this.websocket.send(JSON.stringify(data));
      this.websocket.send(data);
    },
    reconnect() {
      // if(this.lockReconnect){       //这里很关键，因为连接失败之后之后会相继触发 连接关闭，不然会连接上两个 WebSocket
      //     return
      // }
      // this.lockReconnect = true;
      // this.reconnectData && clearTimeout(this.reconnectData);
      // this.reconnectData = setTimeout(()=>{
      //     this.initWebSocket();
      //     this.lockReconnect = false;
      // },5000)
    },
    heatBeat() {
      // this.timeoutObj && clearTimeout(this.timeoutObj);
      // this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
      // this.timeoutObj = setTimeout(()=>{
      //     this.websocketsend({type:'心跳检测'})   //根据后台要求发送
      //     this.serverTimeoutObj = setTimeout(()=> {
      //         this.websock.close();       //如果  5秒之后我们没有收到 后台返回的心跳检测数据 断开socket，断开后会启动重连机制
      //     }, 5000);
      // }, this.timeout)
    },
    destroyed() {
      // this.lockReconnect = true;
      // this.websock.close()                   //离开路由之后断开websocket连接
      // clearTimeout(this.reconnectData);      //离开清除 timeout
      // clearTimeout(this.timeoutObj);         //离开清除 timeout
      // clearTimeout(this.serverTimeoutObj);   //离开清除 timeout
    },

    //点击浏览器退出或前进时,重新跳转到登录页面
    back(event) {
      const path = this.$route.name;
      if (path === "Login") {
        window.history.pushState(null, null, document.URL); //禁止浏览器后退前进
      }
    },
    handleClick(active) {
      this.active = active;
      this.$nextTick(() => {
        if (this.$refs.ruleForm) this.$refs.ruleForm.clearValidate();
      });
    },
    onFocus() {
      this.readonly = false;
    },
    onBlur() {
      this.readonly = true;
    },
    // 登录 17636244310
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const url = this.active === "first" ? userNameLogin : phoneLogin;
          const params =
            this.active === "first"
              ? {
                  userName: this.ruleForm.userName,
                  password: this.ruleForm.password, // md5加密 md5(this.ruleForm.password)
                  index: 2
                }
              : {
                  phone: this.ruleForm.phone,
                  code: this.ruleForm.message,
                  index: 2
                };
          this.loading = true;
          this.postRequest(url, params)
            .then(res => {
              this.loading = false;
              if (res.code === 200) {
                sessionStorage.setItem("userInfo", JSON.stringify(res.data[0]));
                sessionStorage.setItem(
                  "userId",
                  JSON.stringify(res.data[0].id)
                );
                // 登录成功  拿到角色id
                this.roleId = res.data[0].roleId;
                // console.log(this.roleId);
                this.userId = window.sessionStorage.getItem("userId");
                const userInfo = JSON.parse(
                  window.sessionStorage.getItem("userInfo")
                );
                this.permissionId = userInfo.PermissionType;
                // 调用获取用户所对应的权限
                this.getRole();
                // this.websocketTest();
                window.sessionStorage.removeItem("sendCode");
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch(err => {
              // console.log(err)
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    // 获取用户所拥有的的权限
    getRole() {
      const params = {
        roleId: this.roleId,
        PermissionType: Number(this.permissionId)
      };
      this.postRequest(powerSelNoPage, params).then(res => {
        if (res.code == 200) {
          this.role = res.data;
          // 用户拥有的所有权限
          this.permission(res.data);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    //权限及导航栏过滤拦截
    permission(list) {
      sessionStorage.setItem("list", JSON.stringify(list));
      this.$store.dispatch("filterRouter", list).then(obj => {
        this.$store.dispatch("filterMenus", list).then(() => {
          this.$router.replace(obj.path);
        });
      });
    },
    //发送验证码
    sendCode() {
      // window.sessionStorage.setItem("sendCode", 60);
      const reg = /^1\d{10}$/;
      if (
        !reg.test(this.ruleForm.phone) ||
        !this.ruleForm.phone ||
        this.ruleForm.phone === "" ||
        this.ruleForm.phone === null
      ) {
        this.$refs.ruleForm.validateField("phone");
        return false;
      }
      // let num = this.sendCoude;

      this.postRequest(messageSend, { phone: this.ruleForm.phone })
        .then(res => {
          this.disabled = true;
          const result = window.sessionStorage.getItem("sendCode");
          if (
            result == "" ||
            result == null ||
            result == undefined ||
            result == 0
          ) {
            this.sendCoude = 60;
            this.text = "已发送 " + this.sendCoude + "s";
          }
          this.timer = setInterval(() => {
            this.sendCoude--;
            window.sessionStorage.setItem("sendCode", this.sendCoude);
            this.text = "已发送 " + this.sendCoude + "s";
            if (this.sendCoude <= 0) {
              this.resetCode();
            }
          }, 1000);
          if (res.code !== 200) this.resetCode();
        })
        .catch(err => {
          this.resetCode();
        });
    },
    resetCode() {
      clearInterval(this.timer);
      this.text = "获取验证码";
      this.disabled = false;
    },
    //服务协议
    onChange(val) {
      this.visible = val;
    },
    onConfirm() {
      this.visible = false;
      this.ruleForm.agreement = true;
    },
    handleChange(value) {
      this.$store.commit("CHANGE_PERSISTENCE", { key: "agreement", value });
    },
    // 忘记密码
    forget() {
      this.find = true;
    },
    //立即登录
    changeLogin() {
      this.find = false;
    },
    // 立即注册
    handlerRegister() {
      this.$router.push("/register");
    }
  },
  components: {
    Forget,
    Agreement,
    Register
  },
  destroyed() {
    const that = this;

    window.removeEventListener("popstate", that.back(), false);
  }
};
</script>

<style scoped>
@import "../../assets/style/login.css";

.box {
  width: 100vw;
  height: 100vh;
  position: relative;
  background-color: #fbfbfd;
}

.bg {
  width: 161px;
  height: 37px;
  padding-top: 30px;
  padding-left: 30px;
  display: block;
}

.login {
  width: 960px;
  height: 450px;
  background: #ffffff;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.06);
  opacity: 0.95;
  border-radius: 8px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -450px;
  margin-top: -225px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login_box {
  width: 100%;
  height: 378px;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-top: 20px;
}

.logo {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-left: 80px;
}

.landmark {
  width: 336px;
  height: 300px;
  display: block;
}

.name {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 0 auto;
  text-align: center;
}

.name > span:first-of-type {
  font-size: 30px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  /*line-height: 48px;*/
  color: rgba(62, 63, 66, 1);
}

.name > span:last-of-type {
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  line-height: 48px;
  color: rgba(158, 160, 165, 1);
}

.form {
  width: 378px;
  margin-right: 72px;
}

.tabs {
  margin-bottom: 48px;
}

.tabs > span {
  height: 24px;
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #606266;
  opacity: 1;
  padding-bottom: 24px;
  cursor: pointer;
}

.tabs > span:last-of-type {
  margin-left: 48px;
}

.active {
  color: rgba(64, 158, 255, 1) !important;
  border-bottom: 1px solid rgba(64, 158, 255, 1);
}

.user {
  color: #409eff;
  cursor: pointer;
}

.code {
  line-height: 40px;
  padding: 0 10px;
  cursor: pointer;
}
</style>
